import Vue from 'vue'
// import router from '@/router'
// import store from '@/store'

/**
 * 获取uuid
 */
export function getUUID () {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
    return (c === 'x' ? (Math.random() * 16 | 0) : ('r&0x3' | '0x8')).toString(16)
  })
}

/**
 * 是否有权限
 * @param {*} key
 */
export function isAuth (key) {
  return JSON.parse(sessionStorage.getItem('permissions') || '[]').indexOf(key) !== -1 || false
}

/**
 * 树形数据转换
 * @param {*} data
 * @param {*} id
 * @param {*} pid
 */
export function treeDataTranslate (data, id = 'id', pid = 'parentId') {
  var res = []
  var temp = {}
  for (var i = 0; i < data.length; i++) {
    temp[data[i][id]] = data[i]
  }
  for (var k = 0; k < data.length; k++) {
    if (temp[data[k][pid]] && data[k][id] !== data[k][pid]) {
      if (!temp[data[k][pid]]['children']) {
        temp[data[k][pid]]['children'] = []
      }
      if (!temp[data[k][pid]]['_level']) {
        temp[data[k][pid]]['_level'] = 1
      }
      data[k]['_level'] = temp[data[k][pid]]._level + 1
      temp[data[k][pid]]['children'].push(data[k])
    } else {
      res.push(data[k])
    }
  }
  return res
}

/**
 * 时间戳转具体日期
 * @param {*} millinSeconds
 */
export function formatDate (millinSeconds) {
  var d = new Date(millinSeconds)
  var year = d.getFullYear()
  var month = d.getMonth() + 1
  var date = d.getDate()
  var hour = d.getHours()
  var minute = d.getMinutes()
  var second = d.getSeconds()
  return year + '-' + month + '-' + date + ' ' + hour + ':' + minute + ':' + second
}

/**
 * 时间戳转日期英文
 * @param {*} millinSeconds
 */
export function formatDateEn (millinSeconds) {
  var date = new Date(millinSeconds)
  var monthArr = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Spt', 'Oct', 'Nov', 'Dec']
  var suffix = ['st', 'nd', 'rd', 'th']

  var year = date.getFullYear() // 年
  var month = monthArr[date.getMonth()] // 月
  var ddate = date.getDate() // 日

  if (ddate % 10 < 1 || ddate % 10 > 3) {
    ddate = ddate + suffix[3]
  } else if (ddate % 10 === 1) {
    ddate = ddate + suffix[0]
  } else if (ddate % 10 === 2) {
    ddate = ddate + suffix[1]
  } else {
    ddate = ddate + suffix[2]
  }
  return ddate + ' ' + month + ' ' + year
}

/**
 * 过滤HTML标签
 */
export function removeHTMLTag (str) {
  str = str.replace(/<\/?[^>]*>/g, '')// 去除HTML tag
  str = str.replace(/[ | ]*\n/g, '\n')// 去除行尾空白
  str = str.replace(/\n[\s| | ]*\r/g, '\n')// 去除多余空行
  str = str.replace(/&nbsp;/g, ' ')
  return str
}

/**
 * 获取url参数
 */
export function getQueryVariable (variable) {
  var query = window.location.search.substring(1)
  var vars = query.split('&')
  for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split('=')
    if (pair[0] === variable) { return pair[1] }
  }
  return ''
}

/**
 * 清除登录信息
 */
export function clearLoginInfo () {
  Vue.cookie.delete('token')
  store.commit('resetStore')
  router.options.isAddDynamicMenuRoutes = false
}
